/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.table;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.jianggujin.dbfly.mybatis.JConfiguration;
import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.util.JProviderHelper;
import com.jianggujin.dbfly.util.JDBFlyException;

/**
 * 动态表名生成工具
 * 
 * @author jianggujin
 *
 */
public class JTableNameGeneratorUtils {

    /**
     * 缓存
     */
    private static final Map<Class<? extends JTableNameGenerator>, JTableNameGenerator> CACHE = new ConcurrentHashMap<Class<? extends JTableNameGenerator>, JTableNameGenerator>();

    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 生成动态表名
     * 
     * @param configuration
     * @param document
     * @param parentElement
     * @param entity
     * @param parameterName
     * @throws JDBFlyException
     */
    public static void dynamicTableName(JConfiguration configuration, Document document, Element parentElement,
            JEntity entity, String parameterName) throws JDBFlyException {
        Class<? extends JTableNameGenerator> tableNameGeneratorClass = entity.getTableNameGeneratorClass();
        try {
            JTableNameGenerator tableNameGenerator;
            if (CACHE.containsKey(tableNameGeneratorClass)) {
                tableNameGenerator = CACHE.get(tableNameGeneratorClass);
            } else {
                LOCK.lock();
                try {
                    if (!CACHE.containsKey(tableNameGeneratorClass)) {
                        CACHE.put(tableNameGeneratorClass, tableNameGeneratorClass.newInstance());
                    }
                    tableNameGenerator = CACHE.get(tableNameGeneratorClass);
                } finally {
                    LOCK.unlock();
                }
            }
            tableNameGenerator.generateTableName(configuration, document, parentElement, entity,
                    JProviderHelper.getParameterName(parameterName));
        } catch (Exception e) {
            throw new JDBFlyException("生成动态表名失败", e);
        }
    }

}
